const app = getApp()
const store = app.store

class request {
  constructor() {
    this._header = {
      'Content-type': 'application/json'
    };
    this.base_url = app.globalData.ENVIRONMENT_CONFIG.systemBaseUrl
  }
  /**
   * PUT 请求
   */
  putRequest(url, data, header = this._header) {
    return this.wxRequest(url, data, header, 'PUT')
  }
  /**
   * POST 请求
   */
  postRequest(url, data, header = this._header, hideError) {
    return this.wxRequest(url, data, header, 'POST', hideError)
  }
  /**
   * GET 请求
   */
  getRequest(url, data, header = this._header, hideError) {
    return this.wxRequest(url, data, header, 'GET', hideError)
  }
  /**
   * DELETE 请求
   */
  deleteRequest(url, data, header = this._header) {
    return this.wxRequest(url, data, header, 'DELETE')
  }

  wxRequest(url, data, header, method, hideError) {
    header["Authorization"] = store.getState().systemLoginData.token;
    header["_imId"] = store.getState().systemLoginData.imId;
    return new Promise((resolve, reject) => {
      wx.request({
        url: this.base_url + url,
        data: data,
        header: header,
        method: method,
        success: (res => {
          let data = res.data;
          if (data instanceof Object) {
            if (data.code != 1) {
              reject(data);
              // token过期跳转到登录页面
              if (data.code == 401) {
                wx.showModal({
                  content: '该功能需要登录后才可以使用，是否前往登录页面？',
                  success(res) {
                    store.dispatch({
                      type: 'clear_LoginData'
                    });
                    if (res.confirm) {
                      wx.reLaunch({
                        url: '/pages/login/login',
                      });
                    } else if (res.cancel) {
                      if (getCurrentPages().length > 1) {
                        wx.navigateBack()
                      } else {
                        wx.switchTab({
                          url: '/pages/home/index/index'
                        });
                      }
                    }
                  }
                })

              } else {
                !hideError && setTimeout(() => {
                  wx.showToast({
                    icon: "none",
                    title: data.msg,
                    duration: 4000
                  });
                }, 500);
              }
            } else {
              resolve(data)
            }
          } else {
            try {
              let tdata = JSON.parse(data);
              if (tdata["Response"] && tdata["Response"]["ReturnCode"] == 0) {
                resolve(tdata["Response"]["ResultData"]);
              } else {
                !hideError && setTimeout(() => {
                  let msg = "服务器数据解析异常，请联系管理员";
                  wx.showToast({
                    icon: "none",
                    title: tdata["Response"] ? tdata["Response"]["ReturnInfo"] : msg,
                    duration: 4000
                  });
                }, 500);
                reject(tdata)
              }
            } catch (e) {
              setTimeout(() => {
                wx.showToast({
                  icon: "none",
                  title: "服务器数据解析异常，请联系管理员",
                  duration: 4000
                });
              }, 500)
              reject(e);
            }
          }
        }),
        fail: (res => {
          setTimeout(() => {
            wx.showToast({
              icon: "none",
              title: "网络异常请稍后重试",
              duration: 4000
            });
          }, 500);
          reject(res);
        })
      })
    })
  }
}

export default new request()